package org.westboy.common.task;


import com.sun.media.jfxmedia.MediaManager;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.control.Label;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.westboy.common.base.MediaService;
import org.westboy.common.util.DateUtil;
import org.westboy.mybatis.mapper.MallbuilderProductOrderMapper;

/**
 * Description:
 *
 * @author Jin
 * @create 2018-01-03
 **/
@Component
public class OrderSoundService extends Service<Void> {


    private BooleanProperty isPlay = new SimpleBooleanProperty(false);

    @Autowired
    private MallbuilderProductOrderMapper orderMapper;

    @Autowired
    private MediaService mediaService;

    private static Integer lastSum = 0;



    Task<Void> task = new Task<Void>() {
        @Override protected Void call() throws InterruptedException {
            while (!isCancelled()){
                    Integer count1 = orderMapper.find10SecondOrderCount();
                    Integer count2 =orderMapper.find10SecondOrderCountByPayType();
                    Integer count3 =orderMapper.find10SecondOtherOrderCount();
                    Integer sum = count1+count2+count3;
                    updateTitle(DateUtil.now()+" 查询到新订单 "+sum+" ");
                    if(sum>0) {
                        sum+=lastSum;
                        updateMessage(sum.toString());
                        lastSum=sum;
                        isPlay.setValue(true);
                        if(!mediaService.status().equals(MediaPlayer.Status.PLAYING)) {
                            mediaService.play();
                        }

                    }else if(!mediaService.status().equals(MediaPlayer.Status.PLAYING)){
                        isPlay.setValue(false);
                        updateMessage(sum.toString());
                    }
                    Thread.sleep(10000);
            }
            return null;
        }

        @Override protected void failed() {
            super.failed();
        }

        @Override
        protected void cancelled() {
            super.cancelled();
        }
    };


    @Override
    protected Task<Void> createTask() {
        return task;
    }


    public BooleanProperty isPlayProperty() {
        return isPlay;
    }

    public static void resetLastSum(){
        lastSum=0;
    }

}
